package com.miao.websecurity.config;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.miao.common.entity.R;
import com.miao.common.exceptionhandler.MyException;
import com.miao.common.utils.JWTUtil;
import com.miao.common.utils.ResponseUtil;
import com.miao.websecurity.entity.TokenAdmin;
import lombok.SneakyThrows;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author MiaoWenqing
 * @description: TODO
 * @date 2021/1/16 19:23
 */
public class AuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws IOException, ServletException {


        String token = httpServletRequest.getHeader("access-token");

       if (null!=token&&!"".equals(token)){

           try {
               String json = JWTUtil.analysisToken(token);
               TokenAdmin tokenAdmin = JSON.parseObject(json, TokenAdmin.class);
               ArrayList<SimpleGrantedAuthority> roles = new ArrayList<>();
               for (String s : tokenAdmin.getRoles()) {
                   roles.add(new SimpleGrantedAuthority(s));
               }

               SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(String.valueOf(tokenAdmin.getAdminId()), token, roles));

           }catch (JWTDecodeException e){
               System.out.println("token 错误");
           }





        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
